<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 收货地址模型
 * @author www.dingwei.cn
 */

class ConsumerAddressModel extends MY_Model{
    public $tbUser = 'consumer';
    public $tbAddress = 'consumer_address';

    /**
     * 保存地址
     *
     * @param	array	$data	保存数据
     * @param	integer $id		地址id
     * @param	integer $consumerId		用户id[批量更改]
     * @return	boolean
     */
    public function save($data, $id = 0,$consumerId = 0){

        if( ! $data) return false;
        if($id){
            $this->db->where(array('id' => $id));
            if($this->update($this->tbAddress, $data)){
                return true;
            }
        }elseif ($consumerId){
        	//根据用户批量修改
        	$this->db->where(array('consumer_id' => $consumerId));
        	if($this->update($this->tbAddress, $data)){
        		return true;
        	}
        }else{
            if($id = $this->insert($this->tbAddress, $data)){
                return $id;
            }
        }
    }

    /**
     * 后台获取用户收货地址
     *
     * @return array
     */
	public function adminGetList(){
        $consumerId = intval(get('consumer_id'));
        $address = trim(get('address'));
        $mobile = trim(get('address_mobile'));
        $consignee = trim(get('consignee'));

	    if(!$consumerId)return array();

	    if($address){
	        $this->db->like(array('s.address' => $address));
	        $this->db->or_like(array('s.street' => $address));
        }

        if($consignee){
            $this->db->like(array('s.consignee' => $consignee));
        }

        if($mobile){
            $this->db->like(array('s.mobile' => $mobile));
        }
	    $this->db->where(array('consumer_id' => $consumerId));

	    $this->db->select('s.id,s.consumer_id,s.consignee,s.mobile,s.province,s.city,s.county,s.latitude,s.longitude,
	                    s.address,s.street')
                 ->join($this->tbUser.' u','u.id = s.consumer_id');

        return $this->pagination($this->tbAddress.' s');
    }

    /**
     * 获取地址信息
     * @param $addressId   integer      收货地址id
     * @param $consumerId  integer      消费者id
     * @return array
     * @author zyl
     */
    public function getInfo($addressId = 0, $consumerId = 0){

	    if(! $addressId && ! $consumerId) return array();

	    if ($addressId){
	        $this->db->where('id',$addressId);
	    }
	    
	    if ($consumerId){
	    	$this->db->where('consumer_id',$consumerId);
	    }

	    $this->db->select('id,consumer_id,consignee,mobile,province,city,county,latitude,longitude,address,street,gender');

	    $tA = $this->getOne($this->tbAddress);
	    
	    if ( ! $tA){
	    	return array();
	    }
	    
	    if ($tA){
	    	get_instance()->loadModel('AdmSettingModel', 'mSetting','admin');
	    	$tLocation = $this->mSetting->getLocationNameByIds(array($tA['province'],$tA['city'],$tA['county']));
	    	$tA['county_name'] = $tLocation[$tA['province']]['name'].' '.
                $tLocation[$tA['city']]['name'].' '.
                $tLocation[$tA['county']]['name'];
	    	$tA['_address'] = $tLocation[$tA['province']]['name'].
						    	$tLocation[$tA['city']]['name'].
						    	$tLocation[$tA['county']]['name'].
						    	$tA['address'];
	    	
	    	$tA['address_desc'] = $tA['address'].$tA['street'];
	    }
	    
	    return $tA;
    }

    /**
     * 删除收货地址
     * @param $addressId        收货地址id
     * @param int $consumerId   消费者id
     * @return bool
     */
    public function deleteAddress($addressId, $consumerId){

        if(!$addressId || !$consumerId) return false;

        $this->db->where(array('consumer_id' => $consumerId,'id' => $addressId));

        return $this->delete($this->tbAddress);
    }
    
    
    /**
     * 获取默认地址接口
     * @param unknown $consumerId
     * @return array|array
     * @author zyl
     */
    public function getDefaultAddress($consumerId, $lat = '', $lng = ''){
    	if ( ! $consumerId){
    		return (object)array();
    	}
    	$select = 'id,consignee,gender,mobile,province,city,county,address,street,latitude,longitude';


        if($lat && $lng){
            //距离的Sql
            $distance = ', 10000 as distance';
            if ($lat && $lng){

                $distance = ',if(longitude > 0 and  latitude, ( ( ACOS(SIN(('.$lat.' * 3.1415) / 180 ) *SIN((latitude * 3.1415) / 180 )
    			+ COS((' .$lat.' * 3.1415) / 180 ) * COS((latitude * 3.1415) / 180 ) * COS((' .$lng.
                    ' * 3.1415) / 180 - (longitude * 3.1415) / 180 ) ) * 6378.138) * 1000), 10000) as distance';
            }
            $select .= ','.$distance;
            //获取商家配送范围
            get_instance()->loadModel('AdmSettingModel', 'mSett', 'admin');
            $merchant_distance_limit = $this->mSett->get('merchant_distance_limit');
            $this->db->having('distance <', $merchant_distance_limit*1000);
            $this->db->order_by('distance asc');
        }else{
            $this->db->where('is_default',2);
        }
        $this->db->select($select);
        $this->db->where('consumer_id',$consumerId);
    	$tA = $this->getOne($this->tbAddress);

    	if ( ! $tA){
    		return (object)array();
    	}
    	
    	get_instance()->loadModel('AdmSettingModel','mSetting','admin');
    	$tAddress = $this->mSetting->getLocationNameByIds(array($tA['province'],$tA['city'],$tA['county']));
    	
    	
    	if ($tA){
    		$tA['mobile'] = substr($tA['mobile'], 0,3).'****'.substr($tA['mobile'], -4);
    		get_instance()->loadModel('AdmSettingModel', 'mSetting','admin');
    		$tLocation = $this->mSetting->getLocationNameByIds(array($tA['province'],$tA['city'],$tA['county']));
    		$tA['address_desc'] = $tLocation[$tA['province']]['name'].
    		$tLocation[$tA['city']]['name'].
    		$tLocation[$tA['county']]['name'].
    		$tA['address'];
            $tA['_mobile'] = substr($tA['mobile'], 0,3).'****'.substr($tA['mobile'], -4);
            $tA['_address_str'] = isset($tAddress[$tA['province']]) ? $tAddress[$tA['province']]['name']:'';
            $tA['_address_str'] .= isset($tAddress[$tA['city']]) ? $tAddress[$tA['city']]['name']:'';
            $tA['_address_str'] .= isset($tAddress[$tA['county']]) ? $tAddress[$tA['county']]['name']:'';
            $tA['_address'] = $tA['address'].$tA['street'];
    	}
    	return $tA;
    }


    /**
     * 获取消费者收货地址
     * @param integer $consumerId 消费者id
     * @param number $page 分页
     * @return array|number|unknown
     * @author zyl
     */
    public function appGetList($consumerId,$page = 1, $all = false, $lat = '', $lng = ''){



        $select = 'id,consignee,gender,mobile,province,city,county,address,street,latitude,longitude,is_default';
    	if($lat && $lng){
            //距离的Sql
            $distance = ', 10000 as distance';
            if ($lat && $lng){

                $distance = ',if(longitude > 0 and  latitude, ( ( ACOS(SIN(('.$lat.' * 3.1415) / 180 ) *SIN((latitude * 3.1415) / 180 )
    			+ COS((' .$lat.' * 3.1415) / 180 ) * COS((latitude * 3.1415) / 180 ) * COS((' .$lng.
                    ' * 3.1415) / 180 - (longitude * 3.1415) / 180 ) ) * 6378.138) * 1000), 10000) as distance';
            }
            $select .= ','.$distance;

            //获取商家配送范围
            get_instance()->loadModel('AdmSettingModel', 'mSett', 'admin');
            $merchant_distance_limit = $this->mSett->get('merchant_distance_limit');

            $this->db->order_by('distance asc');
        }

        $this->db
            ->select($select)
            ->where('consumer_id',$consumerId);

    	if($all){
            $tA = $this->getAll($this->tbAddress);
            $tA['list'] = $tA;
        }else{
            $tA = $this->appPage($this->tbAddress, $page);
        }

    	
    	$addressIds = array();
    	foreach ($tA['list'] as $k=>$v){
    		if (!in_array($v['province'], $addressIds)){
    			$addressIds[] = $v['province'];
    		}
    		if (!in_array($v['city'], $addressIds)){
    			$addressIds[] = $v['city'];
    		}
    		if (!in_array($v['county'], $addressIds)){
    			$addressIds[] = $v['county'];
    		}
            $tA['list'][$k]['over_distance'] = 1;
    		if(isset($v['distance']) && $v['distance'] > $merchant_distance_limit*1000){
                $tA['list'][$k]['over_distance'] = 2;//地址不可用
            }
    	}
    	
    	if ($addressIds){
    		get_instance()->loadModel('AdmSettingModel','mSetting','admin');
    		$tAddress = $this->mSetting->getLocationNameByIds($addressIds);
    		
    		foreach ($tA['list'] as $k=>$v){
    			$tA['list'][$k]['_mobile'] = substr($v['mobile'], 0,3).'****'.substr($v['mobile'], -4);
    			$tA['list'][$k]['_address_str'] = isset($tAddress[$v['province']]) ? $tAddress[$v['province']]['name']:'';
    			$tA['list'][$k]['_address_str'] .= isset($tAddress[$v['city']]) ? $tAddress[$v['city']]['name']:'';
    			$tA['list'][$k]['_address_str'] .= isset($tAddress[$v['county']]) ? $tAddress[$v['county']]['name']:'';
    			$tA['list'][$k]['_address'] = $v['address'].$v['street'];
    			$tA['list'][$k]['gender_str'] = $v['gender'] == 1? '先生':'女士';
    		}
    	}
    	
    	return $tA['list'];
    }

    /**
     * 获取最新的一条
     * @param $consumerId
     * @return string
     */
    public function getTheLatestOne($consumerId){
        $this->db->select('id')
            ->where(array('consumer_id' => $consumerId))
            ->order_by('id desc');
        $tA = $this->getOne($this->tbAddress);
        return isset($tA['id']) ? $tA['id'] : '0';
    }
}